from django.shortcuts import render
from django.http import HttpRequest, HttpResponse
from django.views.decorators.http import require_POST
import simplejson
import bcrypt
from .models import User
from django.db import transaction


@require_POST
def reg(request: HttpRequest):
    body = simplejson.loads(request.body)
    username = body.get("username", 0)
    password = body.get("password", 0)
    role = body.get("role", 0)
    print("!!!!!!!!!!!")
    if username and password and role:
        if User.objects.filter(username=username):
            print("exist")
            return HttpResponse(status=400)
        else:
            print("not exist")
            b_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
            obj = User(username=username, password=b_password, role=role)
            print(obj, obj.__dict__)
            with transaction.atomic():
                obj.save()
            return HttpResponse(status=200)
    else:
        print(2222222222222)
        return HttpResponse(status=400)


